package com.yyh.xiancheng2;
/*线程同步 线程安全*/
public class Test5 {
    public static void main(String[] args) {
        //创建账户对象
        Account account = new Account();
        //创建线程任务对象
        AccountTack task = new AccountTack(account);
        //创建线程对象
        Thread t1 = new Thread(task, "线程1");
        Thread t2 = new Thread(task, "线程2");
        //启动线程
        t1.start();
        t2.start();
    }
}
class Account {
    //默认账户的余额为5000元
    private int money = 5000;
    //取钱的方法
    public void setMoney(int money){
        this.money -= money;
    }
    //查询金额
    public int getMoney(){
        return money;
    }
}
class AccountTack implements Runnable{
    private Account account;
    public AccountTack(Account account){
        this.account = account;
    }
    @Override
    public void run() {
        takeMoney();
    }
    private synchronized void takeMoney(){
        //1.判断账户余额是否大于等于3000元
        if (account.getMoney() >= 3000){
            //可以取钱
            //模拟取钱所花时间，切换线程
            try {
                Thread.sleep(1000);
            }catch (InterruptedException e){
                e.printStackTrace();
            }
            //修改取钱之后的金额
            account.setMoney(3000);
            System.out.println(Thread.currentThread().getName() + "取钱成功，余额为：" + account.getMoney());
        }
        else {
            System.out.println(Thread.currentThread().getName() + "取钱失败，余额不足,余额为："+ account.getMoney());
        }
    }
}